/*
 * @Author: song
 * @Description:红点节点
 * @Date: 2024年04月14日 星期日 17:04:04
 * @Modify:
 */

using System;
using System.Collections.Generic;
using UnityEngine;

namespace Function.RedPoint
{
    public class RedPointNode
    {
        [Tooltip("计数")] public int _num;
        [Tooltip("类型")] public SRedPointType _nodeType;
        [Tooltip("父节点")] public RedPointNode _parent;
        [Tooltip("计数回调")] public Func<int> _numFunc;
        [Tooltip("子节点")] public List<RedPointNode> _childs = new List<RedPointNode>();
        [Tooltip("view层")] public List<Action<RedPointNode>> _viewAction = new List<Action<RedPointNode>>();

        /// <summary>
        /// 是否是叶子节点
        /// </summary>
        /// <returns></returns>
        public bool Leaf()
        {
            return _childs.Count == 0;
        }

        /// <summary>
        /// 刷新计数
        /// </summary>
        public void SetNum()
        {
            int curNum = 0;
            bool leaf = Leaf();
            if (leaf)
            {
                curNum = _numFunc.Invoke();
            }
            else
            {
                foreach (var child in _childs)
                {
                    curNum += child._num;
                }
            }

            if (curNum != _num)
            {
                _num = curNum;
                if (_viewAction != null)
                {
                    foreach (var action in _viewAction)
                    {
                        action?.Invoke(this);
                    }
                }

                var parent = _parent;
                while (parent != null && parent._nodeType != SRedPointType.Root)
                {
                    parent.SetNum();
                    parent = parent._parent;
                }
            }
        }
    }
}